﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace ScriptUtilities
{
    public class Settings
    {
        public static Settings UserSettings = new Settings();

        public const string FileName = "UserConfig.xml";

        //public static String ConfigPath => $"{FileName}";
        public static string ConfigPath => $"{Directory}\\{FileName}";

        public static string Directory => Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

        public List<FieldEntry> FieldLookup { get; set; } = new List<FieldEntry>();

        public List<MotionEntry> MotionLookup { get; set; } = new List<MotionEntry>();

        public void SaveSettings()
        {
            var xmlserializer = new XmlSerializer(GetType());
            var ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);

            using (var fs = new FileStream(ConfigPath, FileMode.Create, FileAccess.Write))
            {
                xmlserializer.Serialize(fs, this, ns);
            }
        }

        public static Settings TryLoadSettings()
        {
            try
            {
                if (!File.Exists(ConfigPath))
                    File.Create(ConfigPath);

                var xmlserializer = new XmlSerializer(typeof(Settings));
                using (var fs = new MemoryStream(File.ReadAllBytes(ConfigPath)))
                {
                    return (Settings)xmlserializer.Deserialize(fs);
                }
            }
            catch (Exception)
            {
                return new Settings();
            }
        }

        public struct FieldEntry
        {
            public string InputField;
            public List<string> OutputFields;

            public FieldEntry(string input, List<string> output)
            {
                InputField = input;
                OutputFields = output;
            }
        }

        public struct MotionEntry
        {
            public string InputMotion;
            public string OutputMotion;

            public MotionEntry(string input, string output)
            {
                InputMotion = input;
                OutputMotion = output;
            }
        }
    }
}
